import React, { useState, useCallback } from 'react';
import { AudioCompatibility } from '../../utils/audioUtils';

interface DiagnosticResult {
  browser?: ReturnType<typeof AudioCompatibility.getBrowserInfo>;
  support?: ReturnType<typeof AudioCompatibility.checkSupport>;
  microphone?: Awaited<ReturnType<typeof AudioCompatibility.testMicrophoneAccess>>;
  formats?: string[];
  recommendations?: string[];
}

/**
 * 语音识别诊断组件
 * 用于测试设备兼容性和权限
 */
const VoiceDiagnostics: React.FC = () => {
  const [diagnosticResult, setDiagnosticResult] = useState<DiagnosticResult | null>(null);
  const [isRunning, setIsRunning] = useState(false);

  const runDiagnostics = useCallback(async () => {
    setIsRunning(true);
    try {
      // console.log('🔍 开始语音识别诊断...');
      const result = await AudioCompatibility.performDiagnostics();
      setDiagnosticResult(result);
      // console.log('🔍 诊断完成:', result);
    } catch (error) {
      console.error('🔍 诊断失败:', error);
      setDiagnosticResult({
        recommendations: [`诊断失败: ${error instanceof Error ? error.message : '未知错误'}`]
      });
    } finally {
      setIsRunning(false);
    }
  }, []);

  const renderStatus = (value: boolean) => (
    <span className={`px-2 py-1 rounded text-sm ${value ? 'bg-green-600 text-white' : 'bg-red-600 text-white'}`}>
      {value ? '✅ 支持' : '❌ 不支持'}
    </span>
  );

  const renderSection = (title: string, children: React.ReactNode) => (
    <div className="mb-6 p-4 bg-gray-800 rounded-lg">
      <h3 className="text-lg font-semibold text-white mb-3">{title}</h3>
      {children}
    </div>
  );

  return (
    <div className="max-w-4xl mx-auto p-6 bg-gray-900 text-white">
      <div className="mb-6">
        <h2 className="text-2xl font-bold mb-4">🎤 语音识别诊断工具</h2>
        <p className="text-gray-300 mb-4">
          此工具可以帮助您检测设备的语音识别兼容性和排查问题
        </p>
        
        <button
          onClick={runDiagnostics}
          disabled={isRunning}
          className={`px-6 py-2 rounded-lg font-medium transition-colors ${
            isRunning 
              ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
              : 'bg-blue-600 text-white hover:bg-blue-700'
          }`}
        >
          {isRunning ? '诊断中...' : '开始诊断'}
        </button>
      </div>

      {diagnosticResult && (
        <div className="space-y-6">
          {/* 浏览器信息 */}
          {diagnosticResult.browser && renderSection(
            '🌐 浏览器信息',
            <div className="grid grid-cols-2 gap-4">
              <div>
                <span className="text-gray-400">浏览器:</span>
                <span className="ml-2 text-white">{diagnosticResult.browser.name} {diagnosticResult.browser.version}</span>
              </div>
              <div>
                <span className="text-gray-400">设备类型:</span>
                <span className="ml-2 text-white">{diagnosticResult.browser.isMobile ? '移动设备' : '桌面设备'}</span>
              </div>
              <div>
                <span className="text-gray-400">WebRTC支持:</span>
                <span className="ml-2">{renderStatus(diagnosticResult.browser.supportsWebRTC)}</span>
              </div>
            </div>
          )}

          {/* 功能支持 */}
          {diagnosticResult.support && renderSection(
            '🔧 功能支持',
            <div className="grid grid-cols-2 gap-4">
              <div className="flex justify-between items-center">
                <span className="text-gray-400">getUserMedia:</span>
                {renderStatus(diagnosticResult.support.getUserMedia)}
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-400">MediaRecorder:</span>
                {renderStatus(diagnosticResult.support.mediaRecorder)}
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-400">AudioContext:</span>
                {renderStatus(diagnosticResult.support.audioContext)}
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-400">WebSocket:</span>
                {renderStatus(diagnosticResult.support.webSocket)}
              </div>
            </div>
          )}

          {/* 麦克风状态 */}
          {diagnosticResult.microphone && renderSection(
            '🎤 麦克风状态',
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-gray-400">设备检测:</span>
                {renderStatus(diagnosticResult.microphone.hasDevices)}
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-400">权限获取:</span>
                {renderStatus(diagnosticResult.microphone.hasPermission)}
              </div>
              {diagnosticResult.microphone.devices && diagnosticResult.microphone.devices.length > 0 && (
                <div>
                  <span className="text-gray-400">检测到的设备:</span>
                  <div className="mt-2 space-y-1">
                    {diagnosticResult.microphone.devices.map((device, index) => (
                      <div key={index} className="text-sm text-gray-300 pl-4">
                        • {device.label || `设备 ${index + 1}`} ({device.deviceId.substr(0, 8)}...)
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {diagnosticResult.microphone.error && (
                <div className="p-3 bg-red-900 border border-red-600 rounded text-red-200">
                  <strong>错误:</strong> {diagnosticResult.microphone.error}
                </div>
              )}
            </div>
          )}

          {/* 音频格式支持 */}
          {diagnosticResult.formats && renderSection(
            '🎵 音频格式支持',
            <div>
              {diagnosticResult.formats.length > 0 ? (
                <div className="space-y-1">
                  {diagnosticResult.formats.map((format, index) => (
                    <div key={index} className="text-sm text-gray-300">
                      ✅ {format}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-red-400">❌ 未检测到支持的音频格式</div>
              )}
            </div>
          )}

          {/* 建议 */}
          {diagnosticResult.recommendations && diagnosticResult.recommendations.length > 0 && renderSection(
            '💡 建议',
            <div className="space-y-2">
              {diagnosticResult.recommendations.map((recommendation, index) => (
                <div key={index} className="p-3 bg-yellow-900 border border-yellow-600 rounded text-yellow-200">
                  • {recommendation}
                </div>
              ))}
            </div>
          )}

          {/* 诊断结果汇总 */}
          {renderSection(
            '📊 诊断结果',
            <div className="p-4 bg-gray-700 rounded">
              {diagnosticResult.recommendations && diagnosticResult.recommendations.length === 0 ? (
                <div className="text-green-400 text-lg font-medium">
                  🎉 恭喜！您的设备完全支持语音识别功能
                </div>
              ) : (
                <div className="text-red-400 text-lg font-medium">
                  ⚠️ 检测到一些问题，请查看上方建议进行解决
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default VoiceDiagnostics; 